package com.miracle9.game.server.message;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

public class MessageDecoderUtil1 implements MessageDecoder
{
  private static Logger logger = Logger.getLogger(MessageDecoderUtil1.class.getName());
  
  public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
    throws Exception
  {}
  
  public MessageDecoderResult decodable(IoSession arg0, IoBuffer in)
  {
    try
    {
      in.mark();
      
      int datalen = (int)in.getUnsignedInt();
     /* if (datalen > 65536)
      {
        logger.error("session:" + arg0.getRemoteAddress() + " is asummed to be attack,datalen" + datalen);
        arg0.close(true);
        return MessageDecoderResult.NOT_OK;
      }*/
      if (datalen == 1014001516)
      {
        byte[] requestBytes = new byte[23];
        in.clear();
        in.get(requestBytes);
        
        String msg = new String(requestBytes).trim();
        if (msg.equals("<policy-file-request/>")) {
          return MessageDecoderResult.OK;
        }
        return MessageDecoderResult.NEED_DATA;
      }
      if (datalen == 1952937823)
      {
        byte[] requestBytes = new byte[62];
        in.clear();
        in.get(requestBytes);
        
        String msg = new String(requestBytes).trim();
        if (msg.indexOf("tgw_l7_forward") > -1) {
          return MessageDecoderResult.OK;
        }
        return MessageDecoderResult.NEED_DATA;
      }
      in.reset();
      if (in.remaining() - 4 >= datalen) {
        return MessageDecoderResult.OK;
      }
      return MessageDecoderResult.NEED_DATA;
    }
    catch (Exception e)
    {
      logger.error("data is un-decodable", e);
    }
    return MessageDecoderResult.OK;
  }
  
  public MessageDecoderResult decode(IoSession arg0, IoBuffer in, ProtocolDecoderOutput out)
    throws Exception
  {
    logger.info("xxxxxxx limit = " + in.limit() + ",in = " +in);
    byte[] input = new byte[in.limit()];
    in.get(input, 0, input.length);
    logger.info("aaaaaaaaaaaa  message = " + printHexString(input));
    IoBuffer ioBuffer = IoBuffer.allocate(input.length);
    ioBuffer.put(input, 0, input.length);
    ioBuffer.flip();
    out.write(ioBuffer);
    return MessageDecoderResult.OK;
  }

  public  String printHexString(byte[] b) {
    String res = "";
    for (int i = 0; i < b.length; i++) {
      String hex = Integer.toHexString(b[i] & 0xFF);
      if (hex.length() == 1) {
        hex = '0' + hex;
      }
      res += hex;
    }
    return res;
  }
}
